package com.liwbn.rbac.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liwbn.rbac.core.orm.mybatis.Page;
import com.liwbn.rbac.exception.JsonReException;
import com.liwbn.rbac.model.Role;
import com.liwbn.rbac.service.RoleService;
import com.liwbn.rbac.support.ExceptionCode;
import com.liwbn.rbac.support.JsonReInfo;

/**
 * 系统角色管理
 * 
 * @author liwb 2016年3月7日 下午6:37:15
 */
@Controller
public class RoleManageController {

    @Autowired
    private RoleService roleService;

    /**
     * 系统角色管理页面
     * 
     * @return
     */
    @RequestMapping("/system/role")
    public String showRoleManage() {
        return "system/role";
    }

    @RequestMapping("/system/roledata")
    @ResponseBody
    public String getRoleData(Integer pageNo, Integer pageSize) {
        Page<Role> page = roleService.selectPage(pageNo, pageSize);
        return page.toString();
    }

    @RequestMapping("system/changeRole")
    @ResponseBody
    public String changeRole(Long id, String name, String sign, String desc) {
        if (!StringUtils.isNotBlank(name) || !StringUtils.isNotBlank(sign)) {
            throw new JsonReException(101, ExceptionCode.CODE_101_EXCEPTION,
                    null);
        }
        Role role = new Role();
        role.setRoleName(name);
        role.setRoleSign(sign);
        role.setDescription(desc);
        try {
            if (id == null) {
                // add
                roleService.insert(role);
            } else {
                // update
                role.setId(id);
                roleService.updateByPrimaryKey(role);
            }
        } catch (Exception e) {
            throw new JsonReException(101, ExceptionCode.CODE_101_EXCEPTION, e);
        }
        return new JsonReInfo(100, ExceptionCode.CODE_100_EXCEPTION).toString();
    }

    @RequestMapping("/system/deleteRole")
    @ResponseBody
    public String deleteRole(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            String[] idsArr = ids.split(",");
            List<Long> idsLong = new ArrayList<Long>();
            for (String id : idsArr) {
                if (StringUtils.isNumeric(id)) {
                    idsLong.add(Long.parseLong(id));
                }
            }
            roleService.deleteByIds(idsLong);
        }
        return new JsonReInfo(100, ExceptionCode.CODE_100_EXCEPTION).toString();
    }
}
